﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyCompany.MyProject.Common;
using MyCompany.MyProject.Common.Helper;
using MyCompany.MyProject.Common.HttpContextUser;
using MyCompany.MyProject.IService;
using MyCompany.MyProject.Model;
using MyCompany.MyProject.Model.DTO;
using MyCompany.MyProject.Model.Models;
using MyCompany.MyProject.WebApi.ModelDto.RoleDto;
using Newtonsoft.Json;
using System.Text;

namespace MyCompany.MyProject.WebApi.Controllers;

/// <summary>
/// 角色控制器
/// </summary>
public class RoleController : BasePermissionApiController
{
    private readonly IRoleService _roleService;
    private readonly IMapper _mapper;
    private readonly IUser _user;
    private readonly IWebHostEnvironment _env;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="roleService"></param>
    /// <param name="mapper"></param>
    /// <param name="user"></param>
    /// <param name="env"></param>
    public RoleController(IRoleService roleService, IMapper mapper, IUser user, IWebHostEnvironment env)
    {
        _roleService = roleService;
        _mapper = mapper;
        _user = user;
        _env = env;
    }

    /// <summary>
    /// 获取角色列表
    /// </summary>
    /// <param name="pageIndex"></param>
    /// <param name="pageSize"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    [HttpGet]
    public async Task<MessageModel<PageModel<RoleVo>>> Get(int pageIndex = 1, int pageSize = 10, string key = "")
    {
        if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            key = string.Empty;
        var data = await _roleService.QueryPage(a => a.IsDeleted != true && (a.Name != null && a.Name.Contains(key)), pageIndex, pageSize, " Id desc ");

        return Success(data.ConvertTo<RoleVo>(_mapper), "获取成功");
    }

    /// <summary>
    /// 新增角色信息
    /// </summary>
    /// <param name="roleVo"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<MessageModel<string>> Post(CreateRoleVo roleVo)
    {
        roleVo.CreateId = _user.ID;
        roleVo.CreateBy = _user.Name;
        var id = await _roleService.Add(_mapper.Map<Role>(roleVo));
        //var id = await _roleService.Add(roleVo);
        return id > 0 ? Success(id.ObjToString(), "添加成功") : Failed("添加失败");
    }

    /// <summary>
    /// 更新数据
    /// </summary>
    /// <param name="roleVo"></param>
    /// <returns></returns>
    [HttpPut]
    public async Task<MessageModel<string>> Put(UpdateRoleVo roleVo)
    {
        var model = await _roleService.QueryById( roleVo.Id);
        model.ModifyId = _user.ID;
        model.ModifyBy = _user.Name;
        model = _mapper.Map(roleVo, model);
        var res = await _roleService.Update(model);
        return res ? Success(res.ObjToString(), "更新成功") : Failed("更新失败");
    }

    /// <summary>
    /// 删除数据，支持批量删除
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<MessageModel<string>> Delete([FromBody] long[] ids)
    {
        var data = new MessageModel<string>();
        if (ids.Length > 0)
        {
            var listRoles = await _roleService.QueryByIDs(ids);
            foreach (var role in listRoles)
                role.IsDeleted = true;
            data.success = await _roleService.Update(listRoles);
            if (data.success)
            {
                data.msg = "删除成功";
                data.response = "";
            }
        }
        return data;
    }

    /// <summary>
    /// 根据数据库数据，生成TSV文件，保存到 wwwroot/SeedData/Role.tsv
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public async Task<MessageModel<string>> SaveDataToTsv()
    {
        var data = new MessageModel<string>();
        if (_env.IsDevelopment())
        {
            JsonSerializerSettings jsonSerializer = new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
            };
            var list = await _roleService.Query(a => a.IsDeleted == false);
            var json = JsonConvert.SerializeObject(list, jsonSerializer);
            FileHelper.WriteFile(Path.Combine(_env.WebRootPath, "SeedData", "Role.tsv"), json, Encoding.UTF8);
            data.success = true;
            data.msg = "操作成功";
        }
        else
        {
            data.success = false;
            data.msg = "仅开发环境可用";
        }
        return data;
    }
}
